<?php

namespace App\Http\Controllers\System;

use App\Models\Nav;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class NavController extends Controller
{
    /** 导航管理 */
    public function index(Request $request)
    {
        $type = $request->get('type',1);

        if($request->isMethod('post')){
            $model = Nav::lists($type);
            return $this->data($model);
        }
        return view('system.nav.index',['type'=>$type]);
    }

    /** 导航编辑 */
    public function edit(Request $request)
    {
        $id = $request->input('id');
        $pid = $request->input('pid',0);
        $type = $request->get('type',1);

        if(!empty($id)){
            $model = Nav::find($id);
        }else{
            $model = new Nav();
        }

        if($request->isMethod('post')){
            $data = $request->all();
            $model->name    = $data['name'];
            $model->type    = $type;
            $model->pid     = $data['pid'];
            $model->icon    = $data['icon'];
            $model->link    = $data['link'];
            $model->sort    = $data['sort'];
            $model->save();

            if(isset($data['role'])){
                $role = Role::whereIn('id',$data['role'])->get();
                foreach($role as $item){
                    $access = json_decode($item->access,true);
                    $access[] = $model->id;

                    Role::where('id',$item->id)->update(['access'=>json_encode($access)]);
                }
            }

            return $this->success('操作成功!');

        }


        $nav = Nav::lists($type=$type,$status=false,$structure='plumb','&nbsp;&nbsp;');
        $nav = array_column($nav,'name','id');

        $role   = Role::pluck('name','id')->toArray();

        return view('system.nav.edit',['nav'=>$nav,'role'=>$role,'model'=>$model,'id'=>$id,'pid'=>$pid,'type'=>$type]);
    }

    /** 导航删除 */
    public function del(Request $request)
    {
        $id = $request->input('id');
        DB::table('navs')->where(['id'=>$id])->delete();
        DB::table('navs')->where(['pid'=>$id])->delete();
        return $this->success('删除成功');
    }

    /** 导航排序 */
    public function sort(Request $request)
    {
        $data = $request->input();
        $data['data'] = json_decode($data['data']);

        foreach($data['data'] as $key=>$item){
            $data['data'][$key] = (array)$item;
        }

        $sql = updateBatch($data['data'],'navs');

        DB::update(DB::raw($sql));
        return $this->success('保存成功');
    }

    public function test(Request $request)
    {
//        $trees ='{"code":0,"msg":"获取成功","data":{"trees":[{"name":"用户管理","value":"yhgl","checked":true,"disabled":false}]}]}]}}';
        $trees = [
            ['name'=>'用户管理','id'=>1,'checked'=>true,'disabled'=>false]
        ];

        return $this->data($trees);
    }
}
